package com.xxwu.springiocdi;

import com.xxwu.springiocdi.Component.UserComponent;
import com.xxwu.springiocdi.config.DIConfig;
import com.xxwu.springiocdi.controller.UserController;
import com.xxwu.springiocdi.dao.User;
import com.xxwu.springiocdi.service.UserService;
import org.apache.catalina.core.ApplicationContext;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.stereotype.Component;

@SpringBootApplication
public class SpringIocDiApplication {

    public static void main(String[] args) {
        //获取Spring上下文环境
        ConfigurableApplicationContext context = SpringApplication.run(SpringIocDiApplication.class, args);
        //从Spring上下文环境中获取Bean对象
        //1 UserController.class 是通过类获取，当一个类型有多个对象时，该方法不适用
        UserController userController = context.getBean(UserController.class);
        userController.sayHi();

        //2 Bean的名称都是唯一的，通过Bean名称获取对象，无论一个类有多少个对象都不影响
        UserService userService = (UserService) context.getBean("userService");
        userService.sayHi();

        //3 通过对象名 + 类获取，该方法适用于其它类中有对象名和本类冲突
        UserComponent userComponent = context.getBean("userComponent", UserComponent.class);
        userComponent.sayHi();

        //通过Bean直接获取对象
        User user = context.getBean("user1", User.class);
        System.out.println(user);
        User user2 = context.getBean("user2", User.class);
        System.out.println(user2);

        DIConfig diConfig = context.getBean(DIConfig.class);
        diConfig.print();


    }
}
